package com.sgg.algorithm.sort;

//O(n2)
public class BubbleSort {
    public static void main(String[] args) {
    }

    public static void sort(int[] arr) {
        int size = arr.length;
        for (int i = 0; i < size - 1; i++) {
            for (int j = 0; j < size - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
//            System.out.println("第" + (i + 1) + "次排序后的数组:" + Arrays.toString(arr));
        }
    }

    //优化:一次排序,没有变化,就说明已经有序了
    public static void sortImprove(int[] arr) {
        int size = arr.length;
        boolean flag = false;

        for (int i = 0; i < size - 1; i++) {
            for (int j = 0; j < size - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = true;
                }
            }
//            System.out.println("第" + (i + 1) + "次排序后的数组:" + Arrays.toString(arr));
            if (!flag) {
                break;
            } else {
                flag = false;
            }
        }
    }
}
